package com.example;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class ClassDialogController {
    @FXML private TextField nameField;
    @FXML private TextArea descriptionField;
    @FXML private javafx.scene.control.ComboBox<Major> majorComboBox;
    @FXML private TextField gradeField;

    private Stage dialogStage;
    private Class classObj;
    private Major major;
    private boolean confirmed = false;

    public void setDialogStage(Stage dialogStage) {
        this.dialogStage = dialogStage;
    }

    public void setClass(Class classObj) {
        this.classObj = classObj;
        if (classObj != null) {
            nameField.setText(classObj.getName());
            gradeField.setText(classObj.getGrade());
        }
    }

    public void setMajor(Major major) {
        this.major = major;
        if (majorComboBox != null && major != null) {
            majorComboBox.getSelectionModel().select(major);
        }
    }

    public boolean isConfirmed() {
        return confirmed;
    }

    public Class getClass_() {
        if (classObj == null) {
            return new Class(0, nameField.getText(), major != null ? major.getId() : 0, gradeField.getText(), null);
        } else {
            classObj.setName(nameField.getText());
            classObj.setGrade(gradeField.getText());
            if (majorComboBox != null && majorComboBox.getValue() != null) {
                classObj.setMajorId(majorComboBox.getValue().getId());
            }
            return classObj;
        }
    }

    @FXML
    private void handleConfirm() {
        if (isInputValid()) {
            confirmed = true;
            dialogStage.close();
        }
    }

    @FXML
    private void handleCancel() {
        dialogStage.close();
    }

    private boolean isInputValid() {
        String errorMessage = "";
        if (nameField.getText() == null || nameField.getText().trim().isEmpty()) {
            errorMessage += "班级名称不能为空\n";
        }
        if (gradeField.getText() == null || gradeField.getText().trim().isEmpty()) {
            errorMessage += "年级不能为空\n";
        }
        if (errorMessage.length() == 0) {
            return true;
        } else {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("输入错误");
            alert.setHeaderText(null);
            alert.setContentText(errorMessage);
            alert.showAndWait();
            return false;
        }
    }
} 